'use strict';

const base_RESTful = require('../core/base_RESTful.js');
const { config_cookies } = require('../config/config.js');
const jwt = require('jsonwebtoken');
const ms = require('ms');
const CreateUser = {
  username: 'string',
  pwd: 'string',
  roleid: 'int',
};

const LoginRule = {
  username: 'string',
  pwd: 'string',
};

// exports.index = async () => {};

// 创建用户
exports.create = async ctx => {
  const _this = new base_RESTful(ctx);
  const rq_data = ctx.request.body;
  const service = ctx.service;

  ctx.validate(CreateUser);
  if (ctx.request.body.username === 'root') {
    _this.error({
      code: '5000',
      msg: '用户名不能为root',
      data: [],
    });
  }

  const result = await service.user.createUser(rq_data.username, rq_data.pwd, rq_data.roleid);

  if (result) {
    _this.success([]);
  } else {
    _this.error([]);
  }
};

// 查找用户
exports.show = async ctx => {
  const _this = new base_RESTful(ctx);
  const service = ctx.service;
  const user = service.user;

  const result = await user.find(ctx.params.id);

  if (result) {
    // _this.success();
    ctx.body = ctx.session.user;
  } else {
    _this.errorF();
  }
};

// 修改用户信息
exports.edit = async ctx => {
  const _this = new base_RESTful(ctx);
  const service = ctx.service;
  const user = service.user;

  const result = await user.find(ctx.params);

  _this.judge_result(result);
};

// 更新用户信息
// exports.update = async () => {};

// 删除用户信息
// exports.destroy = async () => {};

/**
 * @description 登录
 *
 *
 */

exports.login = async ctx => {
  const _this = new base_RESTful(ctx);
  const service = ctx.service;
  const user = service.user;

  const { pwd, username } = ctx.request.body;
  ctx.validate(LoginRule);

  // 检查 账号密码
  ctx.logger.info('username', username);
  ctx.logger.info('pwd', pwd);

  const result = await user.findUsername(username, pwd);

  if (result.code === 404) {
    _this.error({
      code: result.code,
      msg: result.msg,
    });
  }

  // ctx.login(user, [{ id: result.id }]);

  const edit_data = {};
  const now_time = new Date().getTime();

  ctx.logger.info('firstName_____', result.FirstLoginTime);
  ctx.logger.info('find_result', result);

  // 判断是否找到 用户
  const arr_result = Object.keys(result);

  if (arr_result.length === 0 || result === undefined) {
    ctx.body = {
      code: '4000',
      msg: 'not found',
      data: [],
    };
    return false;
  }

  delete result.code;
  const edit_result = await user.editUser(username, result, edit_data);

  // 设置 token
  const temp_user = {
    id: result.id,
  };
  const token = ctx.app.jwt.sign(temp_user, ctx.app.config.jwt.secret);
  ctx.header.token = token;

  if (edit_result) {
    ctx.body = {
      code: 2000,
      msg: 'suc',
      data: {token},
    };
  } else {
    ctx.body = {
      code: 5000,
      msg: 'fail',
      data: [],
    };
  }
};

exports.logout = async ctx => {
  // const token = ctx.get("token");
  // const {
  //   id,
  // } = jwt.decode(token)
  // console.log("token______")
  // console.log(id)
  console.log("====logout====")
  ctx.header.token =  null
  
    ctx.body = {
      code: 2000,
      msg: '登出成功',
    };
  
  
  // ctx.cookies.set('user', null, {
  //   httpOnly: true, // 默认就是 true
  //   encrypt: true, // 加密传输
  //   overwrite: true, // 相同key 就会覆盖
  //   maxAge: ms('1d'), // 过期时间 2分钟
  // });
};

exports.info = async ctx => {
  const _this = new base_RESTful(ctx);
  const rq_data = ctx.request.body;
  const service = ctx.service;
  const token = ctx.get("token");

  const {
    id 
  } = jwt.decode(token);
  id == "" ?id = null:"";

  if (!id) {
    _this.error({
      code: '5000',
      msg: '没有此用户',
      data: [],
    });
  }
  
  console.log("id")
  console.log(id)
  const result = await service.user.find(id);
  console.log("result+++++++")
  console.log(result)
  console.log(result.result[0].RoleName)
  result.result[0].roles = [result.result[0].RoleName];
  delete result.result[0].RoleName;
  console.log("after delete");
  console.log(result[0]);
  if (result) {
    ctx.body = {
      code: 2000,
      msg: '获取用户信息成功',
      data: result.result[0]
    };
  } else {
    console.log("error")
    _this.error({
      code:5000,
      msg:"获取用户数据失败",
      data:[]
    });
  }
};